<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Operators in C#</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="C#, learn C#, operators, programming, language, .NET, Mono">
<meta name="description" content="This part of the C# tutorial covers operators.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>



<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>



<h1>Operators</h1>

<p>
In this part of the C# tutorial, we will talk about operators. 
</p>

<p>
Expressions are constructed from operands and operators. The operators of 
an expression indicate which operations to apply to the operands. 
The order of evaluation of operators in an expression is determined by the 
<b class="keyword">precedence</b> and <b class="keyword">associativity</b> 
of the operators
</p>

<p>
An <b class="keyword">operator</b> is a special symbol which indicates 
a certain process is carried out. Operators in programming languages are 
taken from mathematics. Programmers work with data. The operators are used 
to process data. An <b class="keyword">operand</b> is one of the inputs 
(arguments) of an operator.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
The following table shows a set of operators used in the C# language.
</p>

<table> 
  <tr> 
    <th>Category</th> 
    <th>Symbol</th>
  </tr> 
  <tr> 
    <td>Sign operators</td>
    <td><code>+   -</code></td>     
  </tr> 
  <tr class="gray"> 
    <td>Arithmetic</td>
    <td><code>+   -   *   /   %</code></td>     
  </tr> 
  <tr> 
    <td>Logical (boolean and bitwise)</td> 
    <td><code>&amp;   |   ^   !   ~   &amp;&amp;   ||   true   false</code></td> 
  </tr> 
  <tr class="gray">
    <td>String concatenation</td> 
    <td><code>+</code></td> 
  </tr> 
  <tr>
    <td>Increment, decrement</td>
    <td><code>++ --</code></td> 
  </tr> 
  <tr class="gray">
    <td>Shift</td> 
    <td><code>&lt;&lt; &gt;&gt;</code></td> 
  </tr> 
  <tr>
    <td>Relational</td>
    <td><code>==   !=   &lt;   &gt;   &lt;=   &gt;=</code></td> 
  </tr> 
  <tr class="gray"> 
    <td>Assignment</td> 
    <td><code>=   +=   -=   *=   /=   %=   &amp;=   |=   ^=   &lt;&lt;=   &gt;&gt;= </code></td> 
  </tr> 
  <tr>
    <td>Member access</td>
    <td><code>.</code></td> 
  </tr> 
  <tr class="gray">
    <td>Indexing</td>
    <td><code>[]</code></td> 
  </tr> 
  <tr>
    <td>Cast</td>
    <td><code>()</code></td> 
  </tr> 
  <tr class="gray">
    <td>Ternary</td>
    <td><code>?:</code></td> 
  </tr> 
  <tr> 
    <td>Delegate concatenation and removal</td> 
    <td><code>+  -</code></td> 
  </tr> 
  <tr class="gray"> 
    <td>Object creation</td> 
    <td><code>new</code></td> 
  </tr> 
  <tr> 
    <td>Type information</td> 
    <td><code>as   is   sizeof   typeof   </code></td> 
  </tr> 
  <tr class="gray"> 
    <td>Overflow exception control</td> 
    <td><code>checked unchecked</code></td> 
  </tr> 
  <tr> 
    <td>Indirection and address</td> 
    <td><code>*   -&gt;   []   &amp;</code></td> 
  </tr> 
  <tr class="gray"> 
    <td>Lambda</td> 
    <td><code>=&gt;</code></td> 
  </tr> 
</table> 

<br>

<p>
An operator usually has one or two operands. Those operators that work 
with only one operand are called <b class="keyword">unary operators</b>. 
Those who work with two operands are called <b class="keyword">binary operators</b>. 
There is also one ternary operator (?:), which works with three operands.
</p>

<p>
Certain operators may be used in different contexts. For example the + operator.
From the above table we can see, that it is used in different cases. 
It adds numbers, concatenates strings or delegates; indicates the sign
of a number. We say, that the operator is <b class="keyword">overloaded</b>. 
</p>

<h2>Sign operators</h2>

<p>
There are two sign operators. + and -. They are used to indicate or
change the sign of a value. 
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(2);
        Console.WriteLine(+2);
        Console.WriteLine(-2);
    }
}
</pre>

<p>
+ and - signs indicate the sign of a value. The plus sign can be used 
to indicate that we have a positive number. It can be omitted and it
is mostly done so.
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        int a = 1;
        Console.WriteLine(-a);    // prints -1
        Console.WriteLine(-(-a)); // prints 1
    }
}
</pre>

<p>
The minus sign changes the sign of a value.  
</p>



<h2>The assignment operator</h2>


<p>
The assignment operator <b>=</b> assigns a value to a variable. A <b class="keyword">variable</b> 
is a placeholder for a value. In mathematics, the <b>=</b> operator has a different
meaning. In an equation, the <b>=</b> operator is an equality operator. The left 
side of the equation is equal to the right one. 
</p>

<pre class="code">
int x = 1;
Console.WriteLine(x); // prints 1
</pre>

<p>
Here we assign a number to the x variable. 
</p>

<pre class="code">
x = x + 1;
Console.WriteLine(x);
</pre>

<p>
The previous expression does not make sense in mathematics. But it is legal in programming. 
The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x. 
</p>

<pre class="code">
3 = x;
</pre>

<p>
This code example results in syntax error. We cannot assign a value to a literal. 
</p>

<h2>Concatenating strings</h2>

<p>
In C# the + operator is also used to concatenate strings. 
</p>


<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        Console.WriteLine("Return " + "of " + "the king.");
    }
}
</pre>

<p>
We join three strings together using string concatenation operator. 
</p>

<pre>
$ ./catstrings.exe 
Return of the king.
</pre>

<p>
And this is, what we get. 
</p>


<h2>Increment, decrement operators</h2>

<p>
Incrementing or decrementing a value by one is a common task in 
programming. C# has two convenient operators for this. ++ and --.
</p>

<pre>
x++;
x = x + 1;
...
y--;
y = y - 1;
</pre>

<p>
The above two pairs of expressions do the same.
</p>


<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        int x = 6;
         
        x++;
        x++;

        Console.WriteLine(x);
     
        x--;
        Console.WriteLine(x);
    }
}
</pre>

<p>
In the above example, we demonstrate the usage of both 
operators.
</p>

<pre class="explanation">
int x = 6;
  
x++;
x++;
</pre>

<p>
We initiate the x variable to 6. Then we increment the 
x two times. Now the variable equals to 8.
</p>

<pre class="explanation">
x--;
</pre>

<p>
We use the decrement operator. Now the variable equals to
7.
</p>

<pre>
$ ./incdec.exe 
8
7
</pre>

<p>
And here is the output of the example. 
</p>


<h2>Arithmetic operators</h2>

<p>
The following is a table of arithmetic operators in C#.
</p>

<table>
<tr>
<th>Symbol</th><th>Name</th>
</tr>
<tr><td>+</td><td>Addition</td></tr>
<tr class="gray"><td>-</td><td>Subtraction</td></tr>
<tr><td>*</td><td>Multiplication</td></tr>
<tr class="gray"><td>/</td><td>Division</td></tr>
<tr><td>%</td><td>Remainder</td></tr>
</table>


<p>
The following example shows arithmetic operations.
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        int a = 10;
        int b = 11;
        int c = 12;

        int add = a + b + c;
        int sb = c - a;
        int mult = a * b;
        int div = c / 3;
        int rem = c % a;
        
        Console.WriteLine(add);
        Console.WriteLine(sb);
        Console.WriteLine(mult);
        Console.WriteLine(div);
        Console.WriteLine(rem);
    }
}
</pre>

<p>
In the preceding example, we use addition, subtraction, multiplication,
division and remainder operations. This is all familiar from the mathematics.
</p>

<pre class="explanation">
int rem = c % a;
</pre>

<p>
The % operator is called the remainder or the modulo operator. It finds the 
remainder of division of one number by another. For example, 9 % 4, 9 modulo 4 is 1, 
because 4 goes into 9 twice with a remainder of 1.
</p>

<pre>
$ ./arithmetic.exe 
33
2
110
4
2
</pre>

<p>
Output of the example. 
</p>

<hr class="btm">

<p>
Next we will show the distinction between integer and floating 
point division.
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        int c = 5 / 2;
        Console.WriteLine(c);

        double d = 5 / 2.0;
        Console.WriteLine(d);
    }
}
</pre>

<p>
In the preceding example, we divide two numbers.
</p>

<pre class="explanation">
int c = 5 / 2;
Console.WriteLine(c);
</pre>

<p>
In this code, we have done integer division. The returned value
of the division operation is an integer. When we divide two integers
the result is an integer.
</p>

<pre class="explanation">
double d = 5 / 2.0;
Console.WriteLine(d);
</pre>

<p>
If one of the values is a double or a float, we perform a
floating point division. In our case, the second operand 
is a double so the result is a double.
</p>

<pre>
$ ./division.exe 
2
2.5
</pre>

<p>
Result of the division.exe program. 
</p>


<h2>Boolean operators</h2>

<p>
In C#, we have the following logical operators. 
Boolean operators are also called logical. 
</p>

<table>
<tr>
<th>Symbol</th><th>Name</th>
</tr>
<tr><td>&amp;&amp;</td><td>logical and</td></tr>
<tr class="gray"><td>||</td><td>logical or</td></tr>
<tr><td>!</td><td>negation</td></tr>
</table>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        int x = 3;
        int y = 8;

        Console.WriteLine(x == y); 
        Console.WriteLine(y > x);

        if (y > x)
        {
            Console.WriteLine("y is greater than x");
        }
    }
}
</pre>

<p>
Many expressions result in a boolean value. Boolean values are used
in conditional statements. 
</p>

<pre class="explanation">
Console.WriteLine(x == y); 
Console.WriteLine(y > x);
</pre>

<p>
Relational operators always result in a boolean value. These two lines
print false and true. 
</p>

<pre class="explanation">
if (y > x)
{
    Console.WriteLine("y is greater than x");
}
</pre>

<p>
The body of the <code>if</code> statement is executed only if the condition 
inside the parentheses is met. The y > x returns true, so the message 
"y is greater than x" is printed to the terminal. 
</p>

<hr class="btm">

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        bool a = true &amp;&amp; true;
        bool b = true &amp;&amp; false;
        bool c = false &amp;&amp; true;
        bool d = false &amp;&amp; false;

        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
        Console.WriteLine(d);
    }
}
</pre>

<p>
Example shows the logical and operator. 
It evaluates to true only if both operands are true.
</p>

<pre>
$ ./andoperator.exe 
True
False
False
False
</pre>

<hr class="btm">

<p>
The logical or || operator evaluates to true, 
if either of the operands is true.
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        bool a = true || true;
        bool b = true || false;
        bool c = false || true;
        bool d = false || false;

        Console.WriteLine(a);
        Console.WriteLine(b);
        Console.WriteLine(c);
        Console.WriteLine(d);
    }
}
</pre>

<p>
If one of the sides of the operator is true, the outcome of 
the operation is true. 
</p>

<pre>
$ ./orop.exe 
True
True
True
False
</pre>

<hr class="btm">

<p>
The negation operator ! makes true false and false true. 
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(! true);
        Console.WriteLine(! false);
        Console.WriteLine(! (4 &lt; 3));
    }
}
</pre>

<p>
The example shows the negation operator in action.
</p>

<pre>
$ ./negation.exe 
False
True
True
</pre>

<hr class="btm">

<p>
The <code>||</code>, and <code>&amp;&amp;</code> operators 
are short circuit evaluated. <b>Short circuit evaluation</b> means 
that the second argument is only evaluated if the first argument does 
not suffice to determine the value of the expression: when the first 
argument of the logical and evaluates to false, the overall value must
be false; and when the first argument of logical or evaluates to true, 
the overall value must be true. (wikipedia)
Short circuit evaluation is used mainly to improve performance. 
</p>

<p>
An example may clarify this a bit more.  
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        Console.WriteLine("Short circuit");
        if (One() &amp;&amp; Two())
        {
            Console.WriteLine("Pass");
        }

        Console.WriteLine("#############");
        if (Two() || One())
        {
            Console.WriteLine("Pass");
        }
    }

    public static bool One()
    {
        Console.WriteLine("Inside one");
        return false;
    }

    public static bool Two()
    {
        Console.WriteLine("Inside two");
        return true;
    }
}
</pre>

<p>
We have two methods in the example. They are used as operands
in boolean expressions. We will see, if they are called or not.
</p>

<pre class="explanation">
if (One() &amp;&amp; Two())
{
    Console.WriteLine("Pass");
}
</pre>

<p>
The One() method returns false. The short circuit &amp;&amp;
does not evaluate the second method. It is not necessary.
Once an operand is false, the result of the logical conclusion is always
false. Only "Inside one" is only printed to the console. 
</p>

<pre class="explanation">
Console.WriteLine("#############");
if (Two() || One())
{
    Console.WriteLine("Pass");
}
</pre>

<p>
In the second case, we use the || operator and use the Two()
method as the first operand.
In this case, "Inside two" and "Pass" strings are printed to
the terminal. It is again not necessary to evaluate the second
operand, since once the first operand evaluates to true, the 
logical or is always true.
</p>


<pre>
$ ./shortcircuit.exe 
Short circuit
Inside one
#############
Inside two
Pass
</pre>

<p>
Result of the shorcircuit.exe program. 
</p>


<h2>Relational Operators</h2>

<p>
Relational operators are used to compare values. These operators always 
result in boolean value. Relational operators are also called comparison 
operators.
</p>

<table>
<tr>
<th>Symbol</th><th>Meaning</th>
</tr>
<tr><td>&lt;</td><td>less than</td></tr>
<tr class="gray"><td>&lt;=</td><td>less than or equal to</td></tr>
<tr><td>&gt;</td><td>greater than</td></tr>
<tr class="gray"><td>&gt;=</td><td>greater than or equal to</td></tr>
<tr><td>==</td><td>equal to</td></tr>
<tr class="gray"><td>!=</td><td>not equal to</td></tr>
</table>

<pre class="code">
Console.WriteLine(3 &lt; 4); ' prints True
Console.WriteLine(3 == 4); ' prints False
Console.WriteLine(4 &gt;= 3); ' prints True
Console.WriteLine(4 != 3); ' prints True
</pre>

<p>
In C# we use the == to compare numbers. Some languages
like Ada, Visual Basic, or Pascal use = for comparing numbers.
</p>


<h2>Bitwise operators</h2>

<p>
Decimal numbers are natural to humans. Binary numbers are native to computers. 
Binary, octal, decimal or hexadecimal symbols are only notations of the same number. 
Bitwise operators work with bits of a binary number. Bitwise operators are seldom 
used in higher level languages like C#. 
</p>

<table>
<tr>
<th>Symbol</th><th>Meaning</th>
</tr>
<tr><td>~</td><td>bitwise negation</td></tr>
<tr class="gray"><td>^</td><td>bitwise exclusive or</td></tr>
<tr><td>&amp;</td><td>bitwise and</td></tr>
<tr class="gray"><td>|</td><td>bitwise or</td></tr>
</table>

<p>
The <b>bitwise negation operator</b> changes each 1 to 0 and 0 to 1. 
</p>

<pre class="code">
Console.WriteLine(~ 7); // prints -8
Console.WriteLine(~ -8); // prints 7
</pre>

<p>
The operator reverts all bits of a number 7. One of the bits also determines, 
whether the number is negative or not. If we negate all the bits one more 
time, we get number 7 again. 
</p>

<p>
The <b>bitwise and operator</b> performs bit-by-bit comparison between two numbers. 
The result for a bit position is 1 only if both corresponding bits in the operands are 1. 
</p>

<pre>
      00110
   &amp;  00011
   =  00010
</pre>

<p>
The first number is a binary notation of 6. The second is 3. The result is 2. 
</p>

<pre class="code">
Console.WriteLine(6 &amp; 3); // prints 2
Console.WriteLine(3 &amp; 6); // prints 2
</pre>

<p>
The <b>bitwise or operator</b> performs bit-by-bit comparison between two numbers. 
The result for a bit position is 1 if either of the corresponding bits in the operands is 1. 
</p>

<pre>
     00110
   | 00011
   = 00111
</pre>

<p>
The result is <code>00110</code> or decimal 7. 
</p>

<pre class="code">
Console.WriteLine(6 | 3); // prints 7
Console.WriteLine(3 | 6); // prints 7
</pre>

<p>
The <b>bitwise exclusive or operator</b> performs bit-by-bit comparison between two numbers. 
The result for a bit position is 1 if one or the other (but not both) 
of the corresponding bits in the operands is 1. 
</p>

<pre>
      00110
   ^  00011
   =  00101
</pre>

<p>
The result is <code>00101</code> or decimal 5. 
</p>

<pre class="code">
Console.WriteLine(6 ^ 3); // prints 5
Console.WriteLine(3 ^ 6); // prints 5
</pre>


<h2>Compound assignment operators</h2>

<p>
The compound assignment operators consist of two operators. 
They are shorthand operators. 
</p>

<pre class="code">
using System;

public class CSharpApp
{
    static void Main()
    {
        int a = 1;
        a = a + 1;
 
        Console.WriteLine(a); // prints 2
        
        a += 5;
        Console.WriteLine(a); // prints 7
    }
}
</pre>

<p>
The += compound operator is one of these shorthand operators. 
They are less readable than the full expressions but 
experienced programmers often use them. 
</p>

<p>
Other compound operators are: 
</p>

<pre>
-=   *=   /=   %=   &amp;=   |=   &lt;&lt;=   &gt;&gt;= 
</pre>


<h2>Type information</h2>

<p>
Now we will concern ourselves with operators that work with
types.
</p>

<p>
The <code>sizeof</code> operator is used to obtain the size 
in bytes for a value type. The <code>typeof</code> is 
used to obtain the System.Type object for a type. 
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {   
        Console.WriteLine(sizeof(int));
        Console.WriteLine(sizeof(float));
        Console.WriteLine(sizeof(Int32));
        
        Console.WriteLine(typeof(int));
        Console.WriteLine(typeof(float));
    }
}
</pre>

<p>
We use the <code>sizeof</code> and <code>typeof</code> operators.
</p>

<pre>
$ gmcs sizetype.cs
$ ./sizetype.exe 
4
4
4
System.Int32
System.Single
</pre>

<p>
Output. We can see, that the <code>int</code> type is an
alias for <code>System.Int32</code> and the <code>float</code>
is an alias for the <code>System.Single</code> type.
</p>

<hr class="btm">

<p>
The <code>is</code> operator checks if an object is compatible 
with a given type. 
</p>

<pre class="code">
using System;


class Base {}
class Derived : Base {}

public class CSharpApp
{
    static void Main()
    {    
        Base _base = new Base();
        Derived derived = new Derived();

        Console.WriteLine(_base is Base);
        Console.WriteLine(_base is Object);
        Console.WriteLine(derived is Base);
        Console.WriteLine(_base is Derived);
    }
}
</pre>

<p>
We create two objects from user defined types. 
</p>

<pre class="explanation">
class Base {}
class Derived : Base {}
</pre>

<p>
We have a Base and a Derived class. The Derived class
inherits from the Base class. 
</p>

<pre class="explanation">
Console.WriteLine(_base is Base);
Console.WriteLine(_base is Object);
</pre>

<p>
Base equals Base and so the first line print True. 
A Base is also compatible with <code>Object</code> type. This is 
because each class inherits from the mother of all classes,
the <code>Object</code> class. 
</p>

<pre class="explanation">
Console.WriteLine(derived is Base);
Console.WriteLine(_base is Derived);
</pre>

<p>
The derived object is compatible with the
Base class, because it explicitly inherits from
the Base class. On the other hand, the _base
object has nothing to do with the Derived class. 
</p>

<pre>
$ ./isoperator.exe 
True
True
True
False
</pre>

<p>
Output of example.
</p>

<hr class="btm">

<p>
The <code>as</code> operator is used to perform conversions between compatible 
reference types. When the conversion is not possible, the operator returns null.
Unlike the cast operation which raises an exception.
</p>

<pre class="code">
using System;

class Base {}
class Derived : Base {}

public class CSharpApp
{
    static void Main()
    {    
        object[] objects = new object[6];
        objects[0] = new Base();
        objects[1] = new Derived();
        objects[2] = "ZetCode";
        objects[3] = 12;
        objects[4] = 1.4;
        objects[5] = null;

        for (int i=0; i&lt;objects.Length; ++i) 
        {
            string s = objects[i] as string;
            Console.Write ("{0}:", i);

            if (s != null)
                Console.WriteLine (s);
            else
                Console.WriteLine ("not a string");
        }
    }
}
</pre>

<p>
In the above example, we use the <code>as</code> operator to
perform casting. 
</p>

<pre class="explanation">
string s = objects[i] as string;
</pre>

<p>
We try to cast various types to the string type. But only
once the casting is valid. 
</p>

<pre>
$ ./asoperator.exe 
0:not a string
1:not a string
2:ZetCode
3:not a string
4:not a string
5:not a string
</pre>

<p>
Output.
</p>


<h2>Operator precedence</h2>

<p>
The <b>operator precedence</b> tells us which operators are evaluated first. 
The precedence level is necessary to avoid
ambiguity in expressions. 
</p>

<p>
What is the outcome of the following expression? 28 or 40?
</p>

<pre>
 3 + 5 * 5
</pre>

<p>
Like in mathematics, the multiplication operator has a higher 
precedence than addition operator. So the outcome is 28.
</p>

<pre>
(3 + 5) * 5
</pre>

<p>
To change the order of evaluation, we can use parentheses.
Expressions inside parentheses are always evaluated first. 
</p>


<p>
The following table shows common C# operators ordered by
precedence (highest precedence first):
</p> 
 
<table> 
  <tr> 
    <th>Operator(s)</th> 
    <th>Category</th> 
    <th>Associativity</th>
  </tr> 
  <tr class="gray"> 
    <td>Primary</td>
    <td><code>x.y  f(x)  a[x]  x++  x--  new  typeof  default  checked  unchecked</code></td>     
    <td>Left</td>
  </tr> 
  <tr> 
    <td>Unary</td> 
    <td><code>+  -  !  ~  ++x  --x  (T)x</code></td> 
    <td>Left</td>
  </tr> 
  <tr class="gray">
    <td>Multiplicative</td> 
    <td><code>* / %</code></td> 
    <td>Left</td>
  </tr> 
  <tr>
    <td>Additive</td>
    <td><code>+ -</code></td> 
    <td>Left</td> 
  </tr> 
  <tr class="gray">
    <td>Shift</td> 
    <td><code>&lt;&lt; &gt;&gt;</code></td> 
    <td>Left</td>
  </tr> 
  <tr> 
    <td>Equality</td>
    <td><code>== !=</code></td> 
    <td>Right</td> 
  </tr> 
  <tr class="gray">
    <td>Logical AND</td>
    <td><code>&amp;</code></td> 
    <td>Left</td> 
  </tr> 
  <tr>
    <td>Logical XOR</td>
    <td><code>^</code></td> 
    <td>Left</td> 
  </tr> 
  <tr class="gray">
    <td>Logical OR</td>
    <td><code>|</code></td> 
    <td>Left</td> 
  </tr> 
  <tr>
    <td>Conditional AND</td>
    <td><code>&amp;&amp;</code></td> 
    <td>Left</td> 
  </tr> 
  <tr class="gray">
    <td>Conditional OR</td>
    <td><code>||</code></td> 
    <td>Left</td> 
  </tr> 
  <tr class="gray"> 
    <td>Null Coalescing</td> 
    <td><code>??</code></td> 
    <td>Left</td>
  </tr> 
  <tr> 
    <td>Ternary</td> 
    <td><code>?:</code></td> 
    <td>Right</td>
  </tr> 
  <tr class="gray"> 
    <td>Assignment</td> 
    <td><code>=  *=  /=  %=  +=  -=  &lt;&lt;=  >>=  &amp;=  ^=  |=  =></code></td> 
    <td>Right</td>
  </tr> 
</table> 

<p>Operators on the same row of the table have the same precedence.</p> 

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        Console.WriteLine(3 + 5 * 5);
        Console.WriteLine((3 + 5) * 5);

        Console.WriteLine(! true | true);
        Console.WriteLine(! (true | true));
    }
}
</pre>

<p>
In this code example, we show some common expressions. 
The outcome of each expression is dependent on the precedence level.
</p>

<pre class="explanation">
Console.WriteLine(3 + 5 * 5);
</pre>

<p>
This line prints 28. The multiplication operator has a higher precedence
than addition. First the product of 5*5 is calculated. Then 3 is added. 
</p>


<pre class="explanation">
Console.WriteLine(! true | true);
</pre>

<p>
In this case, the negation operator has a higher precedence. First, 
the first true value is negated to false, than the | operator 
combines false and true, which gives true in the end. 
</p>

<pre>
$ ./precedence.exe 
28
40
True
False
</pre>


<h2>Associativity</h2>

<p>
Sometimes the precedence is not satisfactory to determine the outcome 
of an expression. There is another rule called
<b>associativity</b>. The associativity of operators determines 
the order of evaluation of operators with the <b>same</b>
precedence level. 
</p>

<pre>
9 / 3 * 3
</pre>

<p>
What is the outcome of this expression? 9 or 1? The multiplication, 
deletion and the modulo operator are left to right associated. 
So the expression is evaluated this way: <code>(9 / 3) * 3</code> 
and the result is 9.
</p>

<p>
Arithmetic, boolean, relational and bitwise operators are all left 
to right associated. 
</p>


<p>
On the other hand, the assignment operator is right associated. 
</p>

<pre class="code">
int a, b, c, d;
a = b = c = d = 0;
Console.WriteLine("{0} {1} {2} {3}", a, b, c, d); // prints 0 0 0 0 
</pre>

<p>
If the association was left to right, the previous expression would not be possible. 
</p>

<p>
The compound assignment operators are right to left associated. 
</p>

<pre class="code">
int j = 0;
j *= 3 + 1;
Console.WriteLine(j);
</pre>

<p>
You might expect the result to be 1. But the actual result is 0.
Because of the associativity. The expression on the right is 
evaluated first and than the compound assignment operator is applied.
</p>

<h2>The null-coalescing operator</h2>

<p>
The null-coalescing operator (??) is used to define a default value
for a nullable type. It returns the left-hand operand if it is not 
null; otherwise it returns the right operand. When we work with 
databases, we often deal with absent values. These values come as
nulls to the program. This operator is a convenient way to deal 
with such situations. 
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        int? x = null;
        int? y = null;

        int z = x ?? y ?? -1;
        
        Console.WriteLine(z);
    }
}
</pre>

<p>
An example program for null-coalescing operator. 
</p>

<pre class="explanation">
int? x = null;
int? y = null;
</pre>

<p>
Two nullable <code>int</code> types are initiated to <code>null</code>.
</p>

<pre class="explanation">
int z = x ?? y ?? -1;
</pre>

<p>
We want to assign a value to z variable. But it must not be <code>null</code>.
This is our requirement. We can easily use the  null-coalescing operator 
for that. In case both x, y variables are null, we assign -1 to z.
</p>

<pre>
$ ./nullcoalescing.exe 
-1
</pre>

<p>
Output of program.
</p>

<hr class="btm">

<h2>The ternary operator</h2>

<p>
The ternary operator (?:) is a conditional operator. It is a convenient
operator for cases, where we want to pick up one of two values, depending
on the conditional expression.
</p>

<pre>
cond-exp ? exp1 : exp2
</pre>

<p>
If cond-exp is true, exp1 is evaluated and the result is returned. If
the cond-exp is false, exp2 is evaluated and its result is returned.
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        int age = 31;

        bool adult = age >= 18 ? true : false;

        Console.WriteLine("Adult: {0}", adult);
    }
}
</pre>

<p>
In most countries the adulthood is based on your age.
You are adult if you are older than a certain age.
This is a situation for a ternary operator.
</p>

<pre class="explanation">
bool adult = age >= 18 ? true : false;
</pre>

<p>
First the expression on the right side of the assignment
operator is evaluated. The first phase of the ternary operator
is the condition expression evaluation. So if the age is greater
or equal to 18, the value following the ? character is returned.
If not, the value following the : character is returned.
The returned value is then assigned to the adult variable.
</p>

<pre>
$ ./ternary.exe 
Adult: True
</pre>

<p>
A 31 years old person is adult.
</p>


<h2>The Lambda operator</h2>

<p>
The => token is called the lambda operator. It is an operator
taken from functional languages. This operator can make the 
code shorter and cleaner. On the other hand, understanding the
syntax may be tricky. Especially, if a programmer never used a
functional language before. 
</p>

<p>
Wherever we can use a delegate, we also can use a lambda expression.
A definition for a lambda expression is: A lambda expression is an 
anonymous function that can contain expressions and statements. 
On the left side we have a group of data and on the right side an
expression or a block of statements. These statements are applied on
each item of the data. 
</p>

<p>
Also, in lambda expressions we do not have a return keyword. The last
statement is automatically returned. And we do not need to specify
types for our parameters. The compiler will guess the correct parameter
type. This is called type inference. 
</p>

<pre class="code">
using System;
using System.Collections.Generic;

public class CSharpApp
{
    static void Main()
    {
        List&lt;int&gt; list = new List&lt;int&gt;() 
            { 3, 2, 1, 8, 6, 4, 7, 9, 5 };

        List&lt;int&gt; sublist = list.FindAll(val => val &gt; 3);
        
        foreach (int i in sublist)
        {
            Console.WriteLine(i);
        }
    }
}
</pre>

<p>
We have a list of integer numbers. We print all numbers that are
greater than 3. 
</p>

<pre class="explanation">
List&lt;int&gt; list = new List&lt;int&gt;() 
    { 3, 2, 1, 8, 6, 4, 7, 9, 5 };
</pre>

<p>
We have a generic list of integers.
</p>

<pre class="explanation">
List&lt;int&gt; sublist = list.FindAll(val => val &gt; 3);
</pre>

<p>
Here we use the lambda operator. The <code>FindAll()</code> method
takes a predicate as a parameter. A predicate is a special kind of
a delegate, that returns a boolean value. The predicate is applied
for all items of the list. The <code>val</code> is an input parameter, 
specified without a type. We could explicitly specify the type, but it
is not necessary. The compiler will expect an <code>int</code> type. 
The <code>val</code> is a current input value from the list. It is
compared if it is greater than 3 and a boolean true or false is returned.
Finally, the <code>FindAll()</code> will return all values that met
the condition. They are assigned to the sublist collection.
</p>

<pre class="explanation">
foreach (int i in sublist)
{
    Console.WriteLine(i);
}
</pre>

<p>
The items of the sublist collection are printed to the terminal.
</p>

<pre>
$ ./lambda.exe 
8
6
4
7
9
5
</pre>

<p>
Values from the list of integers that are greater than 3. 
</p>

<pre class="code">
using System;
using System.Collections.Generic;

public class CSharpApp
{
    static void Main()
    {
        List&lt;int&gt; list = new List&lt;int&gt;() 
            { 3, 2, 1, 8, 6, 4, 7, 9, 5 };

        List&lt;int&gt; sublist = list.FindAll( 
            delegate(int i) 
            {
                return i > 3;
            }
        );
        
        foreach (int i in sublist)
        {
            Console.WriteLine(i);
        }
    }
}
</pre>

<p>
This is the same example. We use a anonymous delegate instead
of a lambda expression.
</p>

<h2>Calculating prime numbers</h2>

<p>
We are going to calculate prime numbers.
</p>

<pre class="code">
using System;


public class CSharpApp
{
    static void Main()
    {
        int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 
            9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
            19, 20, 21, 22, 23, 24 };

        Console.Write("Prime numbers: ");

        foreach (int num in nums) 
        {
            if (num == 1 || num == 2 || num == 3)
            {
                Console.Write(num + " ");
                continue;
            }

            int i = (int) Math.Sqrt(num);
            bool isPrime = true;

            while (i > 1)
            { 
                if (num % i == 0)
                {
                    isPrime = false;
                } 
                i--;
            }

            if (isPrime) 
            {
                 Console.Write(num + " ");
            }
        }
        Console.Write('\n');
    }
}
</pre>

<p>
In the above example, we deal with many various operators. A prime 
number (or a prime) is a natural number that has exactly two distinct 
natural number divisors: 1 and itself. We pick up a number and divide 
it by numbers, from 1 up to the picked up number. Actually, we don't have
to try all smaller numbers, we can divide by numbers up to the square
root of the chosen number. The formula will work. We use the remainder 
division operator. 
</p>

<pre class="explanation">
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 
    9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
    19, 20, 21, 22, 23, 24 };
</pre>

<p>
We will calculate primes from these numbers. 
</p>

<pre class="explanation">
if (num == 1 || num == 2 || num == 3)
{
    Console.Write(num + " ");
    continue;
}
</pre>

<p>
We skip the calculations for the 1, 2, 3 numbers. They
are primes. Note the usage of the equality and conditional or
operators. The == has a higher precedence than the || operator.
So we don't need to use parentheses.
</p>

<pre class="explanation">
int i = (int) Math.Sqrt(num);
</pre>

<p>
We are OK if we only try numbers smaller than the square root of
a number in question. 
</p>

<pre class="explanation">
while (i > 1)
{ 
    ...
    i--;
}
</pre>

<p>
This is a while loop. The i is the calculated square root
of the number. We use the decrement operator to decrease
the i by one each loop cycle. When the i is smaller than
1, we terminate the loop. For example, we have number 9.
The square root of 9 is 3. We will divide the 9 number by
3 and 2. This is sufficient for our calculation.
</p>

<pre class="explanation">
if (num % i == 0)
{
    isPrime = false;
} 
</pre>

<p>
This is the core of the algorithm. If the remainder division
operator returns 0 for any of the i values, than the number in
question is not a prime.
</p>

<p>
In this part of the C# tutorial, we covered the operators. 
</p>



<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified October 23, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

